package com.example.opcdemo.opc;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringWriter;

/**
 * @author yupeng
 * @date 2022/4/25 14:47
 * @remark
 */
public class MyStringUtil {

    public static String addZeroForNum(String str, int strLength) {
        str = str == null ? "" : str.trim();
        int strLen = str.length();
        StringBuffer sb;
        while (strLen < strLength) {
            sb = new StringBuffer();
            sb.append("0").append(str);// 左补0
            // sb.append(str).append("0");//右补0
            str = sb.toString();
            strLen = str.length();
        }
        return str;
    }

    public static String[] str2Array(String str, int n) {
        int m = str.length() / n;
        if (m * n < str.length()) {
            m++;
        }
        String[] strs = new String[m];
        int j = -1;
        for (int i = 0; i < str.length(); i++) {
            if (i % n == 0) {//每隔n个
                j++;
                strs[j] = "" + str.charAt(i);
            } else {
                strs[j] = strs[j] + str.charAt(i);
            }
        }
        return strs;
    }

    /**
     * 将文件读取为16进制String
     * Read original File and transfer it into Hex String
     *
     * @return
     * @throws IOException
     */
    public static String readOriginal2Hex(File file) throws IOException {
        FileInputStream fin = new FileInputStream(file);
        StringWriter sw = new StringWriter();

        int len = 1;
        byte[] temp = new byte[len];

        /*16进制转化模块*/
        for (; (fin.read(temp, 0, len)) != -1;) {
            if (temp[0] > 0xf && temp[0] <= 0xff) {
                sw.write(Integer.toHexString(temp[0]));
            } else if (temp[0] >= 0x0 && temp[0] <= 0xf) {//对于只有1位的16进制数前边补“0”
                sw.write("0" + Integer.toHexString(temp[0]));
            } else { //对于int<0的位转化为16进制的特殊处理，因为Java没有Unsigned int，所以这个int可能为负数
                sw.write(Integer.toHexString(temp[0]).substring(6));
            }
        }

        return sw.toString();
    }

    /**
     * ftp上传煤监局测点取值方法
     *
     * @param monitorPointNum
     * @return
     */
    public static String mjjMonitorPointNum(String monitorPointNum) {
        return monitorPointNum.substring(0, 3) + monitorPointNum.substring(5);
    }
}
